package tjs.study.notes.base.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

public class ThreadUtils {
    private static final Logger log = LoggerFactory.getLogger(ThreadUtils.class);

    public static void run(ThreadPoolTaskExecutor threadPoolTaskExecutor, Runnable runnable) {
        ThreadUtils.run(threadPoolTaskExecutor, Arrays.asList(runnable));
    }

    public static void run(ThreadPoolTaskExecutor threadPoolTaskExecutor, List<Runnable> runnables) {
        if (CollectionUtils.isEmpty(runnables)) {
            return;
        }
        if (threadPoolTaskExecutor.getMaxPoolSize() > 1) {
            List<CompletableFuture> tasks = new ArrayList<>(runnables.size());
            runnables.forEach(item -> {
                tasks.add(CompletableFuture.runAsync(item, threadPoolTaskExecutor));
            });
            CompletableFuture.allOf(tasks.toArray(new CompletableFuture[0])).join();
        } else {
            runnables.forEach(runnable -> runnable.run());//如果只有1个线程，则直接当前线程执行，避免线程切换
        }
    }

    public static ThreadPoolTaskExecutor getOne() {
        return getOne("test-");
    }

    public static ThreadPoolTaskExecutor getOne(String threadName) {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 设置核心线程数
        executor.setCorePoolSize(5);
        // 设置最大线程数
        executor.setMaxPoolSize(7);
        // 设置队列容量
        executor.setQueueCapacity(0);
        // 设置线程活跃时间（秒）
        executor.setKeepAliveSeconds(65);
        // 设置默认线程名称
        executor.setThreadNamePrefix(threadName + "-");
        // 设置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.initialize();
        return executor;
    }

    public static void sleepMilliSeconds(int seconds) {
        try {
            Thread.currentThread().sleep(seconds);
        } catch (InterruptedException e) {
            log.error("", e);
        }
    }

}